package com.word.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordUtil {
    public static String readText(String path, String extend) throws IOException, OpenXML4JException, XmlException {
        String content = "";
        if(".doc".equals(extend)){
            FileInputStream fileInputStream = new FileInputStream(path);
            WordExtractor wordExtractor = new WordExtractor(fileInputStream);
            content = wordExtractor.getText();
            wordExtractor.close();
        }else if(".docx".equals(extend)) {
            OPCPackage opcPackage = POIXMLDocument.openPackage(path);
            // 获得文本提取器
            POIXMLTextExtractor textExtractor = new XWPFWordExtractor(opcPackage);
            content = textExtractor.getText();
            textExtractor.close();
        }
//        content = content.replaceAll("[\t\n\r]","");
//        content = content.replaceAll(" ","");
        return content;
    }

    public static List<String> getKeyContent(String content,String keys) {
        List<String> result = new ArrayList<>();
        keys = keys.replaceAll(" and ","(.*)").replaceAll(" or ","|");
        String model = "(.*)"+keys+"(.*)\r\n";
        Pattern pattern = Pattern.compile(model);
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String temp = content.substring(start,end);
            temp = temp.replaceAll("[\t\n\r]","");
            temp = temp.replaceAll(" ","");
            result.add(temp);
        }
        return result;
    }
}
